<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>复选框</title>
    <base href="../../../../../"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >
    <meta name="generator" content="www.leipi.org" />
    <link rel="stylesheet" href="plug-in/Formdesign/js/ueditor/formdesign/bootstrap/css/bootstrap.css">
    <!--[if lte IE 6]>
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap-ie6.css">
    <![endif]-->
    <!--[if lte IE 7]>
    <link rel="stylesheet" type="text/css" href="bootstrap/css/ie.css">
    <![endif]-->
    <link rel="stylesheet" href="plug-in/Formdesign/js/ueditor/formdesign/leipi.style.css">
    <script type="text/javascript" src="plug-in/Formdesign/js/ueditor/formdesign/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="plug-in/Formdesign/js/ueditor/dialogs/internal.js"></script>
	<link id="easyuiTheme" rel="stylesheet" href="plug-in/easyui/themes/default/easyui.css" type="text/css"></link>
    <script type="text/javascript" src="plug-in/easyui/jquery.easyui.min.1.3.2.js"></script>
    <script type="text/javascript">
	$(function(){
		//1.从参数中获取ID
		var id = '';
		editor.ready(function() {
			id = editor.queryCommandValue('serverparam').id; //返回参数值键值对的对象
		 });
		//2.根据ID进行数据源和字段的填充
		//2.1 填充数据源
		$.post(
			'autoFormController.do?getFormDb',		
			{autoFormId:id},
			function(data){
				data = $.parseJSON(data);
				$('#datasource').html(data.msg);
		});
		
		//2.2 绑定change事件,并填充字段
		$("#datasource").change(function(){
			var dbId = $(this).val();
			$.post(
				'autoFormController.do?getFormField',		
				{dbName:dbId,autoFormId:id},
				function(data){
					data = $.parseJSON(data);
					$('#field').html('');
					$('#field').html(data.msg);
			});
		});
        $("#field").change(function(){
            if(this.value!='')
                $G('orgname').value= $(this).find("option:selected")[0].text;
        });
	});
function createElement(type, name)
{     
    var element = null;     
    try {        
        element = document.createElement('<'+type+' name="'+name+'">');     
    } catch (e) {}   
    if(element==null) {     
        element = document.createElement(type);     
        element.name = name;     
    } 
    return element;     
}


//checkboxs
function isIE()
{
    if(window.attachEvent){   
        return true;
    }
    return false;
}
//moveRow在IE支持而在火狐里不支持！以下是扩展火狐下的moveRow
if (!isIE()) {
    function getTRNode(nowTR, sibling) {
        while (nowTR = nowTR[sibling]) if (nowTR.tagName == 'TR') break;
        return nowTR;
    }
    if (typeof Element != 'undefined') {
        Element.prototype.moveRow = function(sourceRowIndex, targetRowIndex) //执行扩展操作
        {
            if (!/^(table|tbody|tfoot|thead)$/i.test(this.tagName) || sourceRowIndex === targetRowIndex) return false;
            var pNode = this;
            if (this.tagName == 'TABLE') pNode = this.getElementsByTagName('tbody')[0]; //firefox会自动加上tbody标签，所以需要取tbody，直接table.insertBefore会error
            var sourceRow = pNode.rows[sourceRowIndex],
            targetRow = pNode.rows[targetRowIndex];
            if (sourceRow == null || targetRow == null) return false;
            var targetRowNextRow = sourceRowIndex > targetRowIndex ? false: getTRNode(targetRow, 'nextSibling');
            if (targetRowNextRow === false) pNode.insertBefore(sourceRow, targetRow); //后面行移动到前面，直接insertBefore即可
            else { //移动到当前行的后面位置，则需要判断要移动到的行的后面是否还有行，有则insertBefore，否则appendChild
                if (targetRowNextRow == null) pNode.appendChild(sourceRow);
                else pNode.insertBefore(sourceRow, targetRowNextRow);
            }
        }
    }
}

/*删除tr*/
function fnDeleteRow(obj)
{
    var oTable = document.getElementById("options_table");
    while(obj.tagName !='TR')
    {
        obj = obj.parentNode;
    }
    oTable.deleteRow(obj.rowIndex);
}
/*上移*/
function fnMoveUp(obj)
{
    var oTable = document.getElementById("options_table");
    while(obj.tagName !='TR')
    {
        obj = obj.parentNode;
    }
    var minRowIndex = 1;
    var curRowIndex = obj.rowIndex;
    if(curRowIndex-1>=minRowIndex)
    {
        oTable.moveRow(curRowIndex,curRowIndex-1); 
    }
    
}
/*下移*/
function fnMoveDown(obj)
{
    var oTable = document.getElementById("options_table");
    while(obj.tagName !='TR')
    {
        obj = obj.parentNode;
    }
    var maxRowIndex = oTable.rows.length;
    var curRowIndex = obj.rowIndex;
    if(curRowIndex+1<maxRowIndex)
    {
        oTable.moveRow(curRowIndex,curRowIndex+1); 
    }
}

/*生成tr*/
function fnAddComboTr(obj)
{
    var oTable = document.getElementById('options_table');
    var new_tr_node= oTable.insertRow(oTable.rows.length);
    var new_td_node0 = new_tr_node.insertCell(0),new_td_node1 = new_tr_node.insertCell(1),new_td_node2 = new_tr_node.insertCell(2);

    var sChecked = '';
    if(obj.checked) sChecked = 'checked="checked"';
    if(!obj.name) obj.name = '';
    if(!obj.value) obj.value = '';
    obj.checkedText=$(obj).attr("checkedText");
    if(!obj.checkedText)obj.checkedText=obj.value;
    new_td_node0.innerHTML = '<td><input type="checkbox" '+sChecked+'></td>';
    new_td_node1.innerHTML = '<td><input type="text" value="'+obj.checkedText+'" name="'+obj.name+'" placeholder="选项值"><input type="hidden" value="'+obj.value+'" name="checkedVal" ></td>';
    new_td_node2.innerHTML ='<td><div class="btn-group"><a title="上移" class="btn btn-small btn-info" href="javascript:void(0);" onclick="fnMoveUp(this)"><i class="icon-white icon-arrow-up"></i></a><a title="下移" class="btn btn-small btn-info" href="javascript:void(0);" onclick="fnMoveDown(this)"><i class="icon-white icon-arrow-down"></i></a><a title="删除" class="btn btn-small btn-default" href="javascript:void(0);" onclick="fnDeleteRow(this)"><i class="icon-ban-circle"></i></a></div></td>';
    return true;
}
function fnAdd() {
    fnAddComboTr({
        "checked":false,
        "name":'leipiNewField',
        "value":''
    });
}
/*组合checkbox*/
function fnParseOptions(gChecked)
{
    var oTable = document.getElementById('options_table');
    var nTr = oTable.getElementsByTagName('tr'),trLength = nTr.length,html="";
    for(var i=0;i<trLength;i++)
    {
        var inputs = nTr[i].getElementsByTagName('input');
        if(inputs.length>0)
        {
            if(!inputs[1].value) continue;
            var sChecked = '';
            if(inputs[0].checked) sChecked = 'checked="checked"';
            html += '<input name="'+inputs[1].name+'" checkedText="'+inputs[1].value+'" value="'+(inputs[2].value==''?inputs[1].value:inputs[2].value)+'" '+sChecked+' type="checkbox"/>'+inputs[1].value+'&nbsp;';
            if(gChecked=='orgchecked1')//竖排
                html+='<br/>';
        }
    }
    //alert(html);
    return html;

}
    </script>
</head>
<body>
<div class="content">
    <table class="table table-bordered table-striped">
     <tr>
        <th><span>控件名称</span><span class="label label-important">*</span></th>
        <th><span>排列方式</span></th>
    </tr>
    <tr>
        <td><input id="orgname" placeholder="必填项" type="text"/> </td>
        <td>
            <label class="radio" title="选项一 选项二"><input id="orgchecked0" checked="checked" name="checked" type="radio"> 横排 </label>
            <label class="radio" title="选项一&#10;选项二"><input id="orgchecked1" name="checked" type="radio" > 竖排 </label>
        </td>
    </tr>
    <tr>
        <th><span>数据源</span></th>
        <th><span>字段</span> </th>
    </tr>
    <tr>
        <td>
           <select id="datasource"></select>
        </td>
        <td>
           <select id="field">
           	  <option selected value=''>请先选择数据源</option>
           </select>
        </td>
    </tr>
    <tr>
        <th><span>数据字典</span></th>
        <th><span>检验规则</span> </th>
    </tr>
    <tr>
        <td>
		<select id="selector"  style="width: 150px"></select>
        <input id="dictCode" type="hidden"   />
        <input type="hidden" id="dictTable" placeholder="字典表">
        <input type="hidden" id="dictText" placeholder="字典Text"></td>
        <td>
            <select type="text" id="datatype" name="datatype" value="" >
            </select>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <table class="table table-hover table-condensed" id="options_table">
                <tr>
                    <th>选中</th>
                    <th>选项值</th>
                    <th>操作</th>
                </tr>
                <!--tr>
                    <td><input type="checkbox" checked="checked"></td>
                    <td><input type="text" value="选项一"></td>
                    <td>
                        <div class="btn-group">
                            <a title="上移" class="btn btn-small btn-info" href="#"><i class="icon-white icon-arrow-up"></i></a>
                            <a title="下移" class="btn btn-small btn-info" href="#"><i class="icon-white icon-arrow-down"></i></a>
                            <a title="删除" class="btn btn-small btn-default"><i class="icon-ban-circle"></i></a>
                        </div>
                    </td>
                </tr-->

            </table>
            <a title="添加选项" class="btn btn-primary" onclick="fnAdd();">添加选项</a>
        </td>
    </tr>


    </table>
</div>
<script type="text/javascript">
var oNode = null,thePlugins = 'checkboxs';
window.onload = function() {
    if( UE.plugins[thePlugins].editdom ){
        oNode = UE.plugins[thePlugins].editdom;
        var gTitle=oNode.getAttribute('title').replace(/&quot;/g,"\"");
        $G('orgname').value = gTitle;
        var checked = oNode.getAttribute('orgchecked');
        checked=='orgchecked1' ? $G('orgchecked1').checked = true : $G('orgchecked0').checked = true;
        //longjinbo 增加属性
         var dictCode= oNode.getAttribute('dictionary');
         if(dictCode){
         	var arraysDict= dictCode.split(',');
			if(arraysDict.length==1){
				$G('dictCode').value =arraysDict[0];
			}else{
				$G('dictCode').value = arraysDict[1];
        		$G('dictTable').value = arraysDict[0];
        		$G('dictText').value = arraysDict[2];
        	}
         }
        var arr1= oNode.getAttribute('autofield');
		if(arr1){
			arr1= arr1.split('.');
			var field = arr1[1]==null?'':arr1[1];
        	var id = '';
			editor.ready(function() {
				id = editor.queryCommandValue('serverparam').id; //返回参数值键值对的对象
			 });
        	$.post(
   				'autoFormController.do?getFormField',		
   				{dbName:arr1[0],autoFormId:id},
   				function(data){
   					data = $.parseJSON(data);
   					$('#field').html('');
   					$('#field').html(data.msg);
   					$('#field').val(field);
   					$("#datasource").val(arr1[0]);
   			});
			//$G('datasource').value = arr1[0];
        	//$G('field').value = field;
        }
        var inputTags = oNode.getElementsByTagName('input');
        var length = inputTags.length;
        var aInputs = [];
        for(var i=0;i<length;i++)
        {
            //testEle.setAttribute("test","aaa"); // 自定义属性 设置  
            //testEle.attributes["test"].nodeValue; // 获得 
            if(inputTags[i].type =='checkbox')
                fnAddComboTr(inputTags[i]);
        }
        var datatype = oNode.getAttribute('datatype');
        $G('datatype').value =datatype;
        loadDataType(datatype);
        var selector=oNode.getAttribute('selector');
        $G("selector").value=selector;
        initCombox(selector);
    }else{
        loadDataType($G('datatype').value);
        initCombox('');
    }

}
dialog.oncancel = function () {
    if( UE.plugins[thePlugins].editdom ) {
        delete UE.plugins[thePlugins].editdom;
    }
};
dialog.onok = function (){
    if($G('orgname').value==''){
        var selectedField=$('#field').find("option:selected");
        var flag=false;
        if(selectedField.length>0){
            selectedField=selectedField.get(0);
            if(selectedField.value!=''){
                $G('orgname').value=selectedField.text;
                flag=true;
            }
        }
        if(!flag){
            alert('请输入控件名称');
            $G('orgname').focus();
            return false;
        }
    }
    var gTitle=$G('orgname').value.replace(/\"/g,"&quot;");
    var gChecked = 'orgchecked0';
    if ($G('orgchecked1').checked) gChecked = 'orgchecked1';
        
 	var datasource=$G('datasource').value;
    var field=$G('field').value;
    //longjinbo 增加数字字典code，与系统标签dgCol dictionary配置方法一致
    var dicCode = $G('dictCode').value;
    var dicTable = $G('dictTable').value;
    var dicText = $G('dictText').value;
    var datatype = $G('datatype').value;
    if(dicTable!=''){
        	dicCode=dicTable+','+dicCode+','+dicText;
    }
    if( !oNode ) {
        try {
            var gTimestamp = new Date().getTime();//相同的gTimestamp为同一组checkbox
            var options = fnParseOptions(gTitle,gChecked,gTimestamp);
            if(!options)
            {
                alert('请添加选项');
                return false;
            }
            //{|- 使用边界，防止用户删除了span标签，程序处理要把边界替换为空
            
            var html = '{|-<span leipiplugins="checkboxs"  autofield="'+datasource+(field!=""?("."+field):"")
            +'" dictionary="'+dicCode+'" datatype="'+datatype+'"  selector="'+$G("selector").value+'"   title="'+gTitle+'">';
                html +=options;
                html +='</span>-|}';
            editor.execCommand('insertHtml',html);
            return true ;
        } catch ( e ) {
            try {
                editor.execCommand('error');
            } catch ( e ) {
                alert('控件异常，请到 [雷劈网] 反馈或寻求帮助！');
            }
            return false;
        }
    } else {
        oNode.setAttribute('title',gTitle);
        oNode.setAttribute('orgchecked',gChecked);
        oNode.setAttribute('dictionary',dicCode);
        oNode.setAttribute('datatype',datatype);
        oNode.setAttribute('selector',$G("selector").value);
        if( datasource != '' ){
            	oNode.setAttribute('autofield',datasource+(field!=''?('.'+field):'') );
            }else{
            	oNode.setAttribute('autofield','');
            }
        oNode.innerHTML = fnParseOptions(gChecked);
        delete UE.plugins[thePlugins].editdom; 
        return true;
    }
};
//longjinbo 系统字典
var systemCache=null;
function initCombox(val){
	$('#selector').append('<option selected value="">请选择数据字典</option>');
	var curl= "systemController.do?typeGroupGrid&field=id,typegroupname,typegroupcode";
	if(!systemCache){
		$.post(curl,		
			function(data){
				var total = data.total;
				if(total < 0){
					alert('no dic type data:');
				}else{
					var data = data.rows;
					jQuery.each(data,function(i,n){
						$('#selector').append('<option value='+ n.id + '>' + n.typegroupname + '</option>');
					});
                    if(val)
                        $('#selector').find("option[value='"+val+"']").attr("selected",true);
				}
				systemCache = total;
			}
		);
	}
}
$('#selector').change(function(){
	onselectCode($(this).val());
});
function onselectCode(id){
var curl= "systemController.do?typeGrid&field=id,typename,typecode&typegroupid="+id;
$.ajax({
  type: 'POST',
  url :curl,
  dataType : 'json',
  success : function(msg){
  		if(msg.success){
  			alert('loading dictable error:'+msg.msg);
  		}else{
  		 	templates =msg.rows;
  		 }
		 var str = "";
	//加选项，需要删除旧数据?
      clearItem();
		for ( var i = 0, tmp; tmp = templates[i++]; ) {
			    fnAddComboTr({
        		"checked":false,
        		"name":'leipiNewField',
                "value":tmp.typecode,
      			 "checkedText":tmp.typename
    			});
        }
  },
});
	for ( var i = 0, tmp; tmp = systemCache[i++]; ) {
		if(tmp.id==id){
			 $G('dictCode').value= tmp.typegroupcode;
		}
	}
}
function clearItem(){
    var trs=$("#options_table tbody").children();
    if(trs.length>1){
        for(var i=1;i<trs.length;i++){
            trs.eq(i).remove();
        }
    }
}
function loadDataType(val){
    $("#datatype").empty();
    $("#datatype").append("<option value=''>无</option>");
    $.ajax({
        url:"systemController.do?typeGrid&",
        data:{typegroupid:"4028838850c35b6a0150c37251e00002",field:"id,typename,typecode"},
        type:"post",
        dataType:"json",
        success:function(data){
            var results=data.rows;
            $.each(results,function(i,dict){
                $("#datatype").append("<option value='"+dict.typecode+"'>"+dict.typename+"</option>");
            })
            if(val)
                $($G('datatype')).find("option[value='"+val+"']").attr("selected","selected");
        }
    });
}
</script>
</body>
</html>